<template>
  <!-- 工单任务责任人表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="700px"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120">
      <div class="formTable">
        <el-card shadow="never" class="table-container">
          <template #header>
            <el-button
              v-show="!props.isReadonly || !formData.id"
              type="success"
              plain
              @click="handleAdd"
            >
              <i-ep-plus />
              新增</el-button
            >
          </template>
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            border
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />

            <el-table-column
              label="负责人姓名"
              props="responsibleId"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.responsibleId'"
                  label-width="0"
                >
                  <el-select
                    style="width: 100%"
                    v-if="!props.isReadonly"
                    v-model="row.responsibleId"
                    placeholder="请选择负责人姓名"
                    clearable
                    @change="(e) => changePerson(e, $index)"
                  >
                    <el-option
                      v-for="item in personList"
                      :label="item.firstName"
                      :value="item.id"
                    />
                  </el-select>
                  <span v-else>{{ row.responsibleName }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="备注" props="remarks" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.remarks'"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.remarks"
                    placeholder="请输入备注"
                    clearable
                  />
                  <span v-else>{{ row.remarks }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="150"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.details.length < 2"
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                  ><i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { forEach } from "lodash-es";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMS8DWORKEREDIT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  workOrderId: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  workOrderId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  responsibleId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  responsibleName: [
    { required: true, message: "请填写负责人", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  version: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
  deleted: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  departmentId: "",
  details: [
    {
      id: "",
      workOrderId: "",
      responsibleId: "",
      responsibleName: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: "",
      deleted: "",
    },
  ],
});

const details1 = {
  id: "",
  workOrderId: "",
  responsibleId: "",
  responsibleName: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const { id, departmentId, details } = newVal;
      Object.assign(formData, {
        id,
        departmentId,
        details,
      });

      getPersonList(departmentId);
      getDel();
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.departmentId = "";

  formData.details = [JSON.parse(JSON.stringify(details1))];
}

const loading = ref(false);

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details1));
  sondata.workOrderId = formData.id;
  formData.details.push(sondata);
};
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  formRef.value.clearValidate();
};

/** 工单任务责任人保存提交 */
function handleSubmit() {
  console.log("编辑", formData.details);

  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/qms/q8dworkorderresponsible/saveBatch",
        method: "post",
        data: formData.details,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
const personList = ref([]);
const getPersonList = async (id) => {
  await request({
    url: "/system/sysUser/getList ",
    method: "post",
    data: {
      departmentId: id,
    },
  }).then((res) => {
    personList.value = res.data;
    console.log("personList", personList.value);
  });
};
const changePerson = (e, index) => {
  if (e) {
    personList.value.forEach((item) => {
      if (item.id == e) {
        formData.details[index].responsibleName = item.firstName;
        formData.details[index].responsibleId = item.id;
      }
    });
  } else {
    formData.details[index].responsibleName = "";
    formData.details[index].responsibleId = "";
  }
};

const getDel = async () => {
  await request({
    url: `/qms/q8dworkorderresponsible/getList`,
    method: "post",
    data: {
      workOrderId: props.workOrderId,
    },
  }).then((res) => {
    if (res.data.length > 0) {
      formData.details = res.data;
    } else {
      formData.details = [JSON.parse(JSON.stringify(details1))];
    }
  });
};
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
